<template>
  <div class="container">
    <Breadcrumb :items="['系统管理', '平台管理']" />
    <a-card class="general-card" title="平台列表">
      <a-row>
        <a-col :flex="1">
          <a-form
            :model="searchForm"
            label-align="left"
            :label-col-props="{ span: 6 }"
            :wrapper-col-props="{ span: 18 }"
            label-layout="inline"
          >
            <a-row :gutter="16">
              <a-col :span="8">
                <a-form-item field="platformName" :label="$t('平台名称')">
                  <a-input
                    v-model="searchForm.platformName"
                    :placeholder="$t('请输入平台名称')"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item field="platformCode" :label="$t('平台编码')">
                  <a-input
                    v-model="searchForm.platformCode"
                    :placeholder="$t('请输入平台编码')"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item field="status" :label="$t('状态')">
                  <a-select
                    v-model="searchForm.status"
                    :placeholder="$t('请选择状态')"
                    allow-clear
                  >
                    <a-option :value="1">{{ $t('启用') }}</a-option>
                    <a-option :value="0">{{ $t('禁用') }}</a-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="16">
              <a-col :span="16">
                <a-space>
                  <a-button type="primary" @click="search">
                    <template #icon>
                      <icon-search />
                    </template>
                    {{ $t('搜索') }}
                  </a-button>
                  <a-button @click="reset">
                    <template #icon>
                      <icon-refresh />
                    </template>
                    {{ $t('重置') }}
                  </a-button>
                </a-space>
              </a-col>
            </a-row>
          </a-form>
        </a-col>
        <a-divider style="height: 32px" direction="vertical" />
        <a-col :flex="'86px'" style="text-align: right">
          <a-button type="primary" @click="openAddDialog">
            <template #icon>
              <icon-plus />
            </template>
            {{ $t('新增') }}
          </a-button>
        </a-col>
      </a-row>
      <a-divider style="margin-top: 0" />
      
      <!-- 平台列表 -->
      <a-table
        :loading="loading"
        :data="platformList"
        :pagination="pagination"
        @page-change="onPageChange"
        @page-size-change="onPageSizeChange"
        stripe
      >
        <template #columns>
          <a-table-column title="序号" :width="80" align="center">
            <template #cell="{ rowIndex }">
              {{ (pagination.current - 1) * pagination.pageSize + rowIndex + 1 }}
            </template>
          </a-table-column>
          <a-table-column title="平台名称" data-index="platformName" :width="160" />
          <a-table-column title="平台编码" data-index="platformCode" :width="150" />
          <a-table-column title="状态" :width="100">
            <template #cell="{ record }">
              <a-tag 
                :color="record.status === 1 ? 'green' : 'red'"
                size="medium"
              >
                {{ record.status === 1 ? '启用' : '禁用' }}
              </a-tag>
            </template>
          </a-table-column>
          <a-table-column title="创建时间" :width="180">
            <template #cell="{ record }">
              {{ formatTime(record.createTime) }}
            </template>
          </a-table-column>
          <a-table-column title="操作" :width="200" fixed="right" align="center">
            <template #cell="{ record }">
              <a-space>
                <a-button type="text" size="small" @click="viewDetail(record)">
                  <template #icon><icon-eye /></template>
                  详情
                </a-button>
                <a-button type="text" size="small" @click="openEditDialog(record)">
                  <template #icon><icon-edit /></template>
                  编辑
                </a-button>
                <a-button type="text" status="danger" size="small" @click="handleDelete(record)">
                  <template #icon><icon-delete /></template>
                  删除
                </a-button>
              </a-space>
            </template>
          </a-table-column>
        </template>
      </a-table>
    </a-card>
    
    <!-- 新增/编辑平台对话框 -->
    <a-modal
      v-model:visible="dialogVisible"
      :title="isEdit ? '编辑平台' : '新增平台'"
      :mask-closable="false"
      :unmount-on-close="false"
      width="500px"
      :footer="false"
      class="platform-modal"
    >
      <a-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-align="left"
        :label-col-props="{ span: 6 }"
        :wrapper-col-props="{ span: 18 }"
        class="platform-form"
      >
        <a-form-item field="platformName" label="平台名称" required>
          <a-input v-model="form.platformName" placeholder="请输入平台名称" />
        </a-form-item>
        <a-form-item field="platformCode" label="平台编码" required>
          <a-input v-model="form.platformCode" placeholder="请输入平台编码" />
        </a-form-item>
        <a-form-item field="status" label="状态" required>
          <a-select v-model="form.status" placeholder="请选择状态">
            <a-option :value="1">启用</a-option>
            <a-option :value="0">禁用</a-option>
          </a-select>
        </a-form-item>
        <a-form-item field="remark" label="备注">
          <a-textarea v-model="form.remark" placeholder="请输入备注" />
        </a-form-item>
        
        <div class="form-footer">
          <a-space>
            <a-button @click="dialogVisible = false">取消</a-button>
            <a-button type="primary" @click="handleSubmit">提交</a-button>
          </a-space>
        </div>
      </a-form>
    </a-modal>
    
    <!-- 平台详情对话框 -->
    <a-modal
      v-model:visible="detailVisible"
      title="平台详情"
      @cancel="detailVisible = false"
      :footer="false"
      width="500px"
    >
      <div v-if="currentPlatform" class="platform-detail">
        <a-descriptions :column="1" bordered size="large">
          <a-descriptions-item label="平台名称">{{ currentPlatform.platformName }}</a-descriptions-item>
          <a-descriptions-item label="平台编码">{{ currentPlatform.platformCode }}</a-descriptions-item>
          <a-descriptions-item label="状态">
            <a-tag :color="currentPlatform.status === 1 ? 'green' : 'red'">
              {{ currentPlatform.status === 1 ? '启用' : '禁用' }}
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="创建时间">{{ formatTime(currentPlatform.createTime) }}</a-descriptions-item>
          <a-descriptions-item label="更新时间">{{ formatTime(currentPlatform.updateTime) }}</a-descriptions-item>
          <a-descriptions-item label="备注">{{ currentPlatform.remark || '无' }}</a-descriptions-item>
        </a-descriptions>
        
        <div class="detail-footer">
          <a-button type="primary" @click="detailVisible = false">关闭</a-button>
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue';
import { Message, Modal } from '@arco-design/web-vue';
import useLoading from '@/hooks/loading';
import axios from 'axios';
import type { FormInstance } from '@arco-design/web-vue';
import {
  IconEye,
  IconEdit,
  IconDelete,
  IconRefresh,
  IconSearch,
  IconPlus
} from '@arco-design/web-vue/es/icon';

// 平台数据接口
interface Platform {
  id: number;
  createTime: string;
  updateTime: string;
  platformName: string;
  platformCode: string;
  status: number;
  remark: string;
}

// 加载状态
const { loading, setLoading } = useLoading();

// 对话框状态
const dialogVisible = ref(false);
const detailVisible = ref(false);
const isEdit = ref(false);
const formRef = ref<FormInstance | null>(null);
const currentPlatform = ref<Platform | null>(null);

// 平台列表
const platformList = ref<Platform[]>([]);

// 搜索表单
const searchForm = reactive({
  platformName: '',
  platformCode: '',
  status: undefined as number | undefined,
});

// 分页
const pagination = reactive({
  total: 0,
  current: 1,
  pageSize: 10,
  showTotal: true,
  showJumper: true,
  showPageSize: true,
});

// 表单数据
interface FormState {
  id?: number;
  platformName: string;
  platformCode: string;
  status: number;
  remark: string;
}

const formInitialState: FormState = {
  platformName: '',
  platformCode: '',
  status: 1,
  remark: '',
};

const form = reactive<FormState>({ ...formInitialState });

// 表单验证规则
const rules = {
  platformName: [{ required: true, message: '请输入平台名称' }],
  platformCode: [{ required: true, message: '请输入平台编码' }],
  status: [{ required: true, message: '请选择状态' }],
};

// 格式化时间
function formatTime(time?: string) {
  if (!time) return '未知';
  return time.replace('T', ' ').substring(0, 19);
}

// 获取平台列表数据
async function fetchData() {
  setLoading(true);
  try {
    const params = {
      pageNum: pagination.current,
      pageSize: pagination.pageSize,
      platformName: searchForm.platformName || undefined,
      platformCode: searchForm.platformCode || undefined,
      status: searchForm.status,
    };

    const response = await axios.get('/api/platform/page', { params });
    platformList.value = response.data.records;
    pagination.total = response.data.total;
  } catch (error) {
    console.error('获取平台列表失败:', error);
    Message.error('获取平台列表失败');
  } finally {
    setLoading(false);
  }
}

// 搜索
function search() {
  pagination.current = 1;
  fetchData();
}

// 重置搜索条件
function reset() {
  searchForm.platformName = '';
  searchForm.platformCode = '';
  searchForm.status = undefined;
  pagination.current = 1;
  fetchData();
}

// 分页变化
function onPageChange(current: number) {
  pagination.current = current;
  fetchData();
}

// 每页条数变化
function onPageSizeChange(pageSize: number) {
  pagination.pageSize = pageSize;
  pagination.current = 1;
  fetchData();
}

// 打开新增对话框
function openAddDialog() {
  isEdit.value = false;
  Object.assign(form, {
    ...formInitialState,
    id: undefined,
  });
  dialogVisible.value = true;
}

// 打开编辑对话框
function openEditDialog(platform: Platform) {
  isEdit.value = true;
  Object.assign(form, {
    id: platform.id,
    platformName: platform.platformName,
    platformCode: platform.platformCode,
    status: platform.status,
    remark: platform.remark || '',
  });
  dialogVisible.value = true;
}

// 查看平台详情
function viewDetail(platform: Platform) {
  currentPlatform.value = platform;
  detailVisible.value = true;
}

// 处理表单提交
const handleSubmit = async () => {
  if (!formRef.value) {
    console.error('表单引用不存在');
    return;
  }
  
  try {
    // 表单验证
    await formRef.value.validate();
    
    setLoading(true);
    
    if (isEdit.value) {
      // 编辑平台
      try {
        const response = await axios.post('/api/platform/update', form);
        
        if (response.code === 200) {
          Message.success('编辑平台成功');
          dialogVisible.value = false;
          // 刷新列表
          fetchData();
        } else {
          Message.error(response.message || '编辑平台失败');
        }
      } catch (error) {
        console.error('编辑平台失败:', error);
        Message.error('编辑平台失败');
      }
    } else {
      // 新增平台
      try {
        const response = await axios.post('/api/platform/add', form);
        
        if (response.code === 200) {
          Message.success('新增平台成功');
          dialogVisible.value = false;
          // 刷新列表
          fetchData();
        } else {
          Message.error(response.message || '新增平台失败');
        }
      } catch (error) {
        console.error('新增平台失败:', error);
        Message.error('新增平台失败');
      }
    }
  } catch (errors) {
    console.error('表单验证失败:', errors);
  } finally {
    setLoading(false);
  }
};

// 删除平台
function handleDelete(platform: Platform) {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除平台 "${platform.platformName}" 吗？此操作不可恢复。`,
    onOk: async () => {
      setLoading(true);
      try {
        const response = await axios.post(`/api/platform/delete/${platform.id}`);
        console.log(response);
        if (response.code === 200) {
          Message.success('删除平台成功');
          // 刷新列表
          fetchData();
        } else {
          Message.error(response.message || '删除平台失败');
        }
      } catch (error) {
        console.error('删除平台失败:', error);
        Message.error('删除平台失败');
      } finally {
        setLoading(false);
      }
    },
  });
}

onMounted(() => {
  // 获取平台列表
  fetchData();
});
</script>

<style scoped lang="less">
.container {
  padding: 0 20px 20px 20px;
}

.platform-modal {
  :deep(.arco-modal-header) {
    border-bottom: 1px solid var(--color-border-2);
    padding: 16px 20px;
    
    .arco-modal-title {
      font-size: 18px;
      font-weight: 500;
    }
  }
  
  :deep(.arco-modal-body) {
    padding: 20px;
  }
}

.platform-form {
  .form-footer {
    display: flex;
    justify-content: center;
    margin-top: 24px;
    
    .arco-space {
      .arco-btn {
        min-width: 80px;
      }
    }
  }
}

.platform-detail {
  .detail-footer {
    margin-top: 24px;
    text-align: center;
  }
}
</style> 